// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const recordCollection = db.collection("recordsData");

// 云函数入口函数
exports.main = async (event, context) => {
  const { id } = event;
  const wxContext = cloud.getWXContext();

  try {
    // 查询是否已存在记录
    const queryRes = await recordCollection
      .where({
        _openid: wxContext.OPENID,
        "recordsdata.id": id,
      })
      .get();

    console.log("查询结果：", queryRes.data);

    if (queryRes.data.length > 0) {
      const record = queryRes.data[0];
      // 找到要删除的记录在 recordsdata 数组中的索引
      const recordIndex = record.recordsdata.findIndex(
        (item) => item.id === id
      );

      if (recordIndex === -1) {
        return {
          success: false,
          message: "未找到要删除的具体记录",
        };
      }

      // 从数组中删除指定索引的记录
      const newRecordsData = record.recordsdata.filter(
        (item) => item.id !== id
      );

      const result = await recordCollection.doc(record._id).update({
        data: {
          recordsdata: newRecordsData,
          updateTime: db.serverDate(),
        },
      });

      return {
        success: true,
        message: "删除成功",
        data: result,
      };
    } else {
      return {
        success: false,
        message: "未找到要删除的记录",
      };
    }
  } catch (err) {
    console.error("删除记录失败：", err);
    return {
      success: false,
      message: "删除失败",
      error: err,
    };
  }
};
